#include "ControlCommandGeneratorPlugin.h"
#include <QDebug>
#include <QPluginLoader>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDir>
#include <QDirIterator>

ControlCommandGeneratorPlugin::ControlCommandGeneratorPlugin(QObject *parent)
    : CameraPluginInterface(parent)
{
    m_configManager = new ProtocolConfigManager(this);
    m_binaryGenerator = new BinaryProtocolGenerator( this);
    m_functionGenerator = new FunctionProtocolGenerator(this);
}

ControlCommandGeneratorPlugin::~ControlCommandGeneratorPlugin()
{
    delete m_binaryGenerator;
    delete m_functionGenerator;
    delete m_configManager;
    qDebug() << "ControlCommandGeneratorPlugin destroyed";
}

void ControlCommandGeneratorPlugin::initialize()
{
    // 初始化插件
    qDebug() << "ControlCommandGeneratorPlugin initialized successfully";
}

QString ControlCommandGeneratorPlugin::pluginName() const
{
    return CONTROL_COMMAND_GENERATOR_PLUGIN_NAME;
}

QString ControlCommandGeneratorPlugin::description() const
{
    return "控制指令生成插件，用于生成设备的二进制协议指令和函数调用指令";
}

bool ControlCommandGeneratorPlugin::activateDevice(const QString &deviceName)
{
    if (deviceName.isEmpty()) {
        qWarning() << "Device name cannot be empty";
        return false;
    }

    // 检查设备是否已激活
    if (m_activatedDevices.contains(deviceName)) {
        // 设备已激活，直接返回成功
        return true;
    }

    // 固定的协议配置文件夹路径（执行目录下的protocol_config目录）
    QString configDir = QDir::currentPath() + "/protocol_config";

    // 查找设备对应的配置文件
    QString configFilePath;
    QDirIterator it(configDir, QStringList() << "*.json", QDir::Files, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QString filePath = it.next();
        QFile file(filePath);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
            file.close();
            if (doc.isObject()) {
                QJsonObject obj = doc.object();
                if (obj.contains("deviceName") && obj["deviceName"].toString() == deviceName) {
                    configFilePath = filePath;
                    break;
                }
            }
        }
    }

    if (configFilePath.isEmpty()) {
        qWarning() << "Config file not found for device:" << deviceName;
        return false;
    }

    // 加载新的配置文件
    bool success = m_configManager->loadConfig(configFilePath, deviceName);
    if (success) {
        // 保存设备名称和配置文件路径
        m_activatedDevices[deviceName] = configFilePath;
        qDebug() << "Device" << deviceName << "activated with config file:" << configFilePath;
    } else {
        qWarning() << "Failed to activate device" << deviceName << "with config file:" << configFilePath;
    }
    return success;
}

bool ControlCommandGeneratorPlugin::deactivateDevice(const QString &deviceName)
{
    if (!m_activatedDevices.contains(deviceName)) {
        return false;
    }

    // 释放设备的配置
    m_configManager->releaseConfig(deviceName);

    // 从激活设备列表中移除
    m_activatedDevices.remove(deviceName);

    qDebug() << "Device" << deviceName << "deactivated";
    return true;
}

bool ControlCommandGeneratorPlugin::isDeviceActivated(const QString &deviceName) const
{
    return m_activatedDevices.contains(deviceName);
}

QStringList ControlCommandGeneratorPlugin::activatedDevices() const
{
    return m_activatedDevices.keys();
}

bool ControlCommandGeneratorPlugin::generateProtocolCommand(const QString &deviceId, const QString &deviceName,const QString &protocolName, const QVariantMap &params)
{
    // 验证设备名称不能为空
    if (deviceName.isEmpty()) {
        qWarning() << "Device name cannot be empty";
        return false;
    }

    // 检查设备是否已激活
    if (!isDeviceActivated(deviceName)) {
        qWarning() << "Device" << deviceName << "is not activated";
        return false;
    }

    // 获取协议信息
    QVariantMap protocolInfo = m_configManager->getProtocolInfo(protocolName, deviceName);
    if (protocolInfo.isEmpty()) {
        qWarning() << "Failed to find protocol info for:" << protocolName << "on device" << deviceName;
        return false;
    }

    QString protocolType = protocolInfo["protocolType"].toString();

    if (protocolType == "binary") {
        // 二进制协议
        int commandType = protocolInfo["commandType"].toInt();
        QVariantMap config = m_configManager->getBinaryProtocolConfig(commandType, deviceName);
         if (config.isEmpty()) {
            return false;
        }
        QByteArray generatedCommand = m_binaryGenerator->generateCommand(config, params);
    } else if (protocolType == "function") {
        // 函数协议
        QString functionName = protocolInfo["functionName"].toString();
        QVariantMap config = m_configManager->getFunctionProtocolConfig(functionName, deviceName);
        if (config.isEmpty()) {
            return false;
        }
        QVariantMap generatedCommand = m_functionGenerator->generateCommand(config, params);
    } else {
        qWarning() << "Unknown protocol type:" << protocolType;
        return false;
    }
    return true;
}

void ControlCommandGeneratorPlugin::onPluginMessage(const QString& sender, const QString& message)
{
    qDebug() << "[ControlCommandGeneratorPlugin Received Message] From:" << sender << "Message:" << message;
    // 处理接收到的消息
}

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
Q_PLUGIN_METADATA(IID "Camera.ControlCommandGeneratorPlugin/1.0")
#endif
